//
//  BanBu_DetailProfileViewController.m
// Halfarea
//
//  Created by banbu3 on 14-2-11.
//
//

#import "BanBu_DetailProfileViewController.h"
#import "AppDataManager.h"
#import "AppCommunicationManager.h"
#import "BanBu_ImageView.h"
#import "BanBu_NavButton.h"
#import "UIViewController+Animation.h"
#import "BanBu_LocationManager.h"
#import "SFHFKeychainUtils.h"
#import "BanBu_VideoAuthenViewController.h"
#import "BanBu_VIPAlert.h"
#import "UIDevice+Helper.h"
@interface BanBu_DetailProfileViewController ()
{
    UIButton *nextBtn;
}
@end


@implementation BanBu_DetailProfileViewController
//#define TABLECOLOUR [UIColor colorWithRed:78.0/255.0 green:201.0/255.0 blue:171.0/255.0 alpha:1]
int selectIndex = -1;    

//#define TABLECOLOUR [UIColor colorWithRed:0.929 green:0.799 blue:0.181 alpha:1.000]
#define TABLECOLOUR [UIColor colorWithRed:0.879 green:0.442 blue:0.774 alpha:1.000]

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    [AppComManager cancalHandlesForObject:self];
    UILabel *lab = (UILabel *)[self.navigationController.navigationBar viewWithTag:10000];
    [lab removeFromSuperview];
    UILabel *lab1 = (UILabel *)[self.navigationController.navigationBar viewWithTag:10001];
    [lab1 removeFromSuperview];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = NSLocalizedString(@"regTitle", nil);
    [self setUpForDismissKeyboard];

    _useDefaultImage = NO;
    self.view.backgroundColor = [UIColor colorWithRed:255.0/255 green:250.0/255 blue:240.0/255 alpha:1.0];
    UITableView *tab = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, __MainScreen_Height-44)];
    tab.separatorStyle = UITableViewCellSeparatorStyleNone;
    tab.backgroundColor = TABLECOLOUR;
    tab.delegate = self;
    tab.dataSource = self;
    [self.view addSubview:tab];
    self.tableView = tab;
    
    BanBu_ImageView *img = [[[BanBu_ImageView alloc] initWithBackGroundImageType:UIImageViewCreatTypeTable] autorelease];
    self.view.backgroundColor = [UIColor colorWithPatternImage:img.image];
    
  
    
    CGFloat btnLen = [NSLocalizedString(@"finishButton", nil) sizeWithFont:[UIFont systemFontOfSize:16] constrainedToSize:CGSizeMake(100, 30)].width;
    BanBu_NavButton *nextButton = [[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeNormal];
    nextButton.position = ButtonPositionRight;
    nextButton.frame=CGRectMake(0, 0, btnLen+20, 30);
    [nextButton addTarget:self action:@selector(complete:) forControlEvents:UIControlEventTouchUpInside];
    [nextButton setTitle:NSLocalizedString(@"finishButton", nil) forState:UIControlStateNormal];
    nextBtn = nextButton;
    [nextBtn setTitleColor:[UIColor colorWithWhite:0.9 alpha:0.8] forState:UIControlStateNormal];
    //    nextButton.titleLabel.font = [UIFont  fontWithName:@"TrebuchetMS-Bold" size:18];
    nextButton.titleLabel.font = [UIFont systemFontOfSize:16];
    UIBarButtonItem *next = [[[UIBarButtonItem alloc] initWithCustomView:nextButton] autorelease];
    self.navigationItem.rightBarButtonItem = next;
    [nextButton release];

}
-(void)checkCanFinish
{
    if(![[_nameField.text stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]] length] )
    {
        [nextBtn setTitleColor:[UIColor colorWithWhite:0.9 alpha:0.8] forState:UIControlStateNormal];
        return;
    }
    if(_sexSeg.selectedIndex == -1)
    {
        [nextBtn setTitleColor:[UIColor colorWithWhite:0.9 alpha:0.8] forState:UIControlStateNormal];
        return;
    }
    if(!_picked)
    {
        [nextBtn setTitleColor:[UIColor colorWithWhite:0.9 alpha:0.8] forState:UIControlStateNormal];
        return;
    }
    [nextBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIndentifier = [NSString stringWithFormat:@"cellindentifiereee%d",indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
    if(!cell)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier] autorelease];
    }
    else
    {
        return cell;
    }

    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    switch (indexPath.row) {
        case 0:
        {
            UITextField *textField = (UITextField *)[cell viewWithTag:111];
            if(!textField)
            {
                UIView *backView1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0,320, 70)];
                backView1.backgroundColor = [UIColor whiteColor];
                [cell.contentView addSubview:backView1];
                [backView1 release];
                
                textField = [[UITextField alloc] initWithFrame:CGRectMake(15, 0,290, 70)];
                textField.font = [UIFont boldSystemFontOfSize:19];
                textField.delegate = self;
                textField.backgroundColor = [UIColor clearColor];
                textField.borderStyle = UITextBorderStyleNone;
                textField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
                textField.textColor = [UIColor blackColor];
//                textField.placeholder = NSLocalizedString(@"headerAndholder", nil);
                //    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
                //    textField.returnKeyType = UIReturnKeyNext;
                [backView1 addSubview:textField];
                [textField release];
                textField.tag = 111;
                _nameField = textField;
                textField.placeholder =NSLocalizedString(@"namePlaceholder", nil);
                if(MyAppDataManager.regDic){
                    NSData *data = [NSData dataFromBase64String:[MyAppDataManager.regDic valueForKey:@"pname_b64"]];
                    NSString *pname_str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                    textField.text = pname_str;
                }
            }
        }
            break;
        case 1:
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            UIView *tempView = [[[UIView alloc] init] autorelease];
            [cell setBackgroundView:tempView];
            [cell setBackgroundColor:[UIColor clearColor]];
            
            UIView *backView2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0,320, 70)];
            backView2.backgroundColor = [UIColor whiteColor];
            [cell.contentView addSubview:backView2];
            [backView2 release];
            
            
        
            BanBu_SexSelectView *sexselect = [[BanBu_SexSelectView alloc] initWithFrame:CGRectMake(35, 10, 250, 50)];
            [sexselect setSelectedIndex:-1];
            sexselect.delegate = self;
            [backView2 addSubview:sexselect];
//            if(MyAppDataManager.regDic){
//                NSInteger sexInteger;
//                if([[MyAppDataManager.regDic valueForKey:@"gender"] isEqualToString:@"m"]){
//                    sexInteger = 0;
//                }else{
//                    sexInteger = 1;
//                }
//                sexselect.selectedIndex =sexInteger;
//            }else{
//                sexselect.selectedIndex = -1;
//            }
            _sexSeg = sexselect;
            [sexselect release];
            
//            NSArray *items = [NSArray arrayWithObjects:[NSString stringWithFormat:@" ♂   %@   ",NSLocalizedString(@"boy",nil)], [NSString stringWithFormat:@" ♀   %@   ",NSLocalizedString(@"girl",nil)],nil];
//            
//            UIView *backView2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0,320, 70)];
//            backView2.backgroundColor = [UIColor whiteColor];
//            [cell.contentView addSubview:backView2];
//            [backView2 release];
//            
//            
//            SVSegmentedControl *seg = [[SVSegmentedControl alloc] initWithSectionTitles:items];
//            seg.center = CGPointMake(160, 35);
//            seg.crossFadeLabelsOnDrag = YES;
//            [seg.thumb setTintColor:[UIColor colorWithRed:221.0/255.0 green:28.0/255.0 blue:19.0/255.0 alpha:1]];
//            seg.backgroundColor = [UIColor colorWithWhite:0 alpha:.2];
//            seg.selectedIndex = 0;
//            if(MyAppDataManager.regDic){
//                NSInteger sexInteger;
//                if([[MyAppDataManager.regDic valueForKey:@"gender"] isEqualToString:@"m"]){
//                    sexInteger = 0;
//                }else{
//                    sexInteger = 1;
//                }
//                seg.selectedIndex =sexInteger;
//            }else{
//                seg.selectedIndex =0;
//                
//            }
//            [seg addTarget:self action:@selector(segmentedControlDidChangeValue:) forControlEvents:UIControlEventValueChanged];
//            _sexSeg = seg;
//            [backView2 addSubview:seg];
//            
//            [seg release];
            

            break;
        case 2:
        {
            
            
            
            
            UIView *backView3 = [[UIView alloc] initWithFrame:CGRectMake(0, 0,320, 590)];
            backView3.backgroundColor = [UIColor whiteColor];
            [cell.contentView addSubview:backView3];
            [backView3 release];
            
            
            UIView *bkView = [[UIView alloc] initWithFrame:CGRectMake(20, 20, 130, 130)];
            bkView.backgroundColor = [UIColor whiteColor];
            bkView.layer.borderColor = [[UIColor grayColor] CGColor];
            bkView.layer.borderWidth = 1.0;
            bkView.layer.cornerRadius = 6.0f;
            [cell.contentView addSubview:bkView];
            [bkView release];
            
            UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(10.0, 10.0, 110, 110)];
            _avatorView = imageview;
            imageview.image = [UIImage imageNamed:@"default.png"];
            [bkView addSubview:imageview];
            [imageview release];
            
            UIButton *btnXiangCe = [UIButton buttonWithType:UIButtonTypeCustom];
            btnXiangCe.frame = CGRectMake(165, 20, 130, 65);
            [btnXiangCe setBackgroundImage:[UIImage imageNamed:@"button_reggallery.png"] forState:UIControlStateNormal];
            [btnXiangCe setTitleEdgeInsets:UIEdgeInsetsMake(35, 0, 10, 0)];
            [btnXiangCe setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            btnXiangCe.titleLabel.font = [UIFont systemFontOfSize:13];
            [btnXiangCe setTitle:NSLocalizedString(@"btnXiangCe", nil) forState:UIControlStateNormal];
            [btnXiangCe addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
            btnXiangCe.tag = 1;
            [cell.contentView addSubview:btnXiangCe];
            
            UIButton *btnCamera = [UIButton buttonWithType:UIButtonTypeCustom];
            btnCamera.frame = CGRectMake(165, 85, 130, 65);
            [btnCamera setBackgroundImage:[UIImage imageNamed:@"button_regtake.png"] forState:UIControlStateNormal];
            [btnCamera setTitleEdgeInsets:UIEdgeInsetsMake(35, 0, 10, 0)];
            [btnCamera setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            btnCamera.titleLabel.font = [UIFont systemFontOfSize:13];
            [btnCamera setTitle:NSLocalizedString(@"btnCamera", nil) forState:UIControlStateNormal];
            [btnCamera addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
            btnCamera.tag = 2;
            [cell.contentView addSubview:btnCamera];
            
            CGSize size = [NSLocalizedString(@"warningLabel1", nil) sizeWithFont:[UIFont boldSystemFontOfSize:16] constrainedToSize:CGSizeMake(300, 1000) lineBreakMode:kTextLineBreakByWordWrapping];
            
            UIView *roundView = [[UIView alloc] initWithFrame:CGRectMake(10, 210, 300, 42+size.height)];
            roundView.layer.cornerRadius = 8.0;
            roundView.layer.borderWidth = 0.8;
            roundView.layer.borderColor = [[UIColor lightGrayColor] CGColor];
            roundView.backgroundColor = [UIColor whiteColor];
            
            UILabel *tipLabel= [[UILabel alloc] initWithFrame:CGRectMake(3, 10, 300, 20)];
            tipLabel.backgroundColor = [UIColor clearColor];
            tipLabel.textAlignment = kTextAlignmentCenter;
            tipLabel.textColor = [UIColor blackColor];
            tipLabel.font = [UIFont boldSystemFontOfSize:16];
            tipLabel.text = NSLocalizedString(@"helpfulTitle", nil);
            [roundView addSubview:tipLabel];
            [tipLabel release];
            
            
            UILabel *helpLabel= [[UILabel alloc] initWithFrame:CGRectMake(0, 35, 300, size.height)];
            helpLabel.backgroundColor = [UIColor clearColor];
            helpLabel.textAlignment = kTextAlignmentLeft;
            helpLabel.numberOfLines = 10;
            helpLabel.textColor = [UIColor darkGrayColor];
            helpLabel.font = [UIFont boldSystemFontOfSize:16];
            helpLabel.text = NSLocalizedString(@"warningLabel1", nil);
            [roundView addSubview:helpLabel];
            [helpLabel release];
            [cell.contentView addSubview:roundView];
            [roundView release];

        }
         break;
            
        default:
            break;
    }
    return cell;
    
}
-(void)popself
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row != 2)
        return 72;
    else
    {
        CGSize size = [NSLocalizedString(@"warningLabel1", nil) sizeWithFont:[UIFont boldSystemFontOfSize:16] constrainedToSize:CGSizeMake(300, 1000) lineBreakMode:kTextLineBreakByWordWrapping];
        return 252+size.height+20;

    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    UITextField *field = (UITextField *)[[self.tableView cellForRowAtIndexPath:indexPath] viewWithTag:111];
    [field becomeFirstResponder];
}
-(void)segmentedControlDidChangeValue:(SVSegmentedControl *)seg
{
    
    if([_nameField isFirstResponder]){
        [_nameField resignFirstResponder];
        
    }
    if(seg.selectedIndex){
        [seg.thumb setTintColor:[UIColor colorWithRed:221.0/255.0 green:28.0/255.0 blue:19.0/255.0 alpha:1]];
        
    }else{
        [seg.thumb setTintColor:[UIColor colorWithRed:30.0/255.0 green:100.0/255.0 blue:175.0/255.0 alpha:1]];
        
    }
    [self checkCanFinish];
}
-(void)sexValueDidChange:(NSInteger)selectIndex
{
    
    if([_nameField isFirstResponder]){
        [_nameField resignFirstResponder];
        
    }
    [self checkCanFinish];
//    if(selectIndex){
//        [seg.thumb setTintColor:[UIColor colorWithRed:221.0/255.0 green:28.0/255.0 blue:19.0/255.0 alpha:1]];
//        
//    }else{
//        [seg.thumb setTintColor:[UIColor colorWithRed:30.0/255.0 green:100.0/255.0 blue:175.0/255.0 alpha:1]];
    
//    }
}
- (void)btnAction:(UIButton *)button
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    if(button.tag == 1)
    {
        if ([UIImagePickerController isSourceTypeAvailable:
             UIImagePickerControllerSourceTypePhotoLibrary]) {
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        }
    }
    else
    {
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    }
    [picker setAllowsEditing:YES];
    [self presentViewController:picker animated:YES];
    [picker release];
    
    
}

#pragma mark  -
- (void)imagePickerController:(UIImagePickerController *)picker
        didFinishPickingImage:(UIImage *)image
                  editingInfo:(NSDictionary *)editingInfo {
    
    
    if(picker.sourceType == UIImagePickerControllerSourceTypeCamera)
        self.imagePathExtension = @"jpg";
    else
    {
        self.imagePathExtension = [[[editingInfo valueForKey:UIImagePickerControllerReferenceURL] pathExtension] lowercaseString];
        if([self.imagePathExtension isEqualToString:@"gif"])
            self.imagePathExtension = @"jpg";
    }
    
    //NSLog(@"geshi:%@",_imagePathExtension);
    
    _picked = YES;
    _avatorView.image = image;
    [picker dismissViewControllerAnimated:YES];
    [self checkCanFinish];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    
    [picker dismissViewControllerAnimated:YES];
}
#pragma mark 上传注册头像参数 图片Data "picformat"  "phone"最后一个参数作用不知
-(void)uploadAvatarImage:(UIImage *)_image
{
    NSData *data = nil;
    data = UIImageJPEGRepresentation(_image, 0.5);
    NSMutableDictionary *uploadDic = [NSMutableDictionary dictionary];
    [uploadDic setValue:@"y" forKey:@"phone"];
    [uploadDic setValue:@"jpg" forKey:@"picformat"];
    [AppComManager uploadRegAvatarImage:data Par:uploadDic delegate:self];
}
-(void)complete:(UIButton *)button
{
    if(![[_nameField.text stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]] length] )
    {
        [TKLoadingView showTkloadingAddedTo:self.view point:CGPointMake(0, 140) title:NSLocalizedString(@"namePlaceholder", nil) activityAnimated:NO duration:1.0];
        //        [TKLoadingView showTkloadingAddedTo:self.view title:@"请输入您的名字" activityAnimated:NO duration:1.0];
        return;
    }
    if(_sexSeg.selectedIndex == -1)
    {
        [TKLoadingView showTkloadingAddedTo:self.view point:CGPointMake(0, 140) title:NSLocalizedString(@"sexSelectFirst", nil)  activityAnimated:NO duration:1.0];
            return;
    }
    //pname base64后存入
    NSString *jsonValue = [[_nameField.text dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
    [MyAppDataManager.regDic setValue:jsonValue forKey:@"pname_b64"];
//    [MyAppDataManager.regDic setValue:@"liberty" forKey:@"pname"];
    
    [MyAppDataManager.regDic setValue:_sexSeg.selectedIndex?@"f":@"m" forKey:@"gender"];

    [self setDefaultHeightWightBlood];
    
    if(_picked)
    {
        [self uploadAvatarImage:_avatorView.image];
        self.navigationController.view.userInteractionEnabled = NO;
        [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"sendAvater", nil) activityAnimated:YES];
    }
    else if(_useDefaultImage)
    {
        NSMutableDictionary *registerInfo = [NSMutableDictionary dictionary];
        [registerInfo setValue:[NSString stringWithFormat:@"%.f",AppLocationManager.curLocation.latitude*1000000] forKey:Latitude];
        [registerInfo setValue:[NSString stringWithFormat:@"%.f",AppLocationManager.curLocation.longitude*1000000] forKey:Longitude];
        [registerInfo setValue:[self getFacePath:[[_facelist objectAtIndex:selectIndex] valueForKey:@"system_facefile"]] forKey:@"1"];
        [registerInfo setValue:[self getFaceName:[[_facelist objectAtIndex:selectIndex] valueForKey:@"system_facefile"]] forKey:@"facefile"];
        [registerInfo setValue:[self getFaceName:[[_facelist objectAtIndex:selectIndex] valueForKey:@"system_facefull"]] forKey:@"facefull"];
        [self saveRegister:registerInfo];
        
        UIAlertView * alert= [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"waitauditNotice", nil) message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"confirmNotice", nil),nil];
        alert.tag = 2;
        [alert show];
        [alert release];
    }
    else
    {
        [TKLoadingView showTkloadingAddedTo:self.view point:CGPointMake(0, 180) title:NSLocalizedString(@"selectAvater", nil) activityAnimated:NO duration:1.0];
        
        return;
    }
    
    
}
-(void)setDefaultHeightWightBlood
{
    NSString *_blood = @"o";
    NSString *_hbody = nil;
    NSString *_wbody = nil;
    if(!_sexSeg.selectedIndex)
    {
        _hbody = @"d";
        _wbody = @"d";
    }
    else
    {
        _hbody = @"b";
        _wbody = @"b";
    }

    [MyAppDataManager.regDic setValue:_blood forKey:@"blood"];
    [MyAppDataManager.regDic setValue:_hbody forKey:@"hbody"];
    [MyAppDataManager.regDic setValue:_wbody forKey:@"wbody"];
}
#pragma mark -注册信息保存到MyAppDataManager 需要参数 “plat” “plong” “facepath” “facefile” “facefull”
-(void)saveRegister:(NSDictionary *)_registerInfo
{
    [MyAppDataManager.regDic addEntriesFromDictionary:_registerInfo];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(alertView.tag == 88888)
    {
        if(buttonIndex == 0)
        {
            BanBu_AppDelegate *delegate = (BanBu_AppDelegate *)[UIApplication sharedApplication].delegate;
            delegate.logined = YES;
            [delegate setViewController:YES];
        }
        else
        {
            BanBu_VideoAuthenViewController *video = [[BanBu_VideoAuthenViewController alloc] initWithRegisterVerify:YES];
            [self.navigationController pushViewController:video animated:YES];
            [video release];
        }
        return;
    }
    
    if(alertView.tag ==111)
    {
        
        [MyAppDataManager.regDic setValue:[UserDefaults valueForKey:@"pushid"] forKey:@"pushid"];
        [self registerUserWith:MyAppDataManager.regDic];
        self.navigationController.view.userInteractionEnabled =NO;
        [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"registering", nil) activityAnimated:YES];
        return;
    }
    
    if(alertView.tag == 222)
    {
        NSMutableDictionary *loginDic = [NSMutableDictionary dictionary];
        [loginDic setValue:[MyAppDataManager.regDic valueForKey:@"email"] forKey:@"email"];
        [loginDic setValue:[MyAppDataManager.regDic valueForKey:@"pass"] forKey:@"pass"];
        [loginDic setValue:[NSString stringWithFormat:@"%.f",AppLocationManager.curLocation.latitude*1000000] forKey:@"plat"];
        [loginDic setValue:[NSString stringWithFormat:@"%.f",AppLocationManager.curLocation.longitude*1000000] forKey:@"plong"];
        [loginDic setValue:[MyAppDataManager.regDic valueForKey:@"regby"] forKey:@"regby"];
        
        BanBu_AppDelegate *delegate = (BanBu_AppDelegate *)[UIApplication sharedApplication].delegate;
        [loginDic setValue:delegate.pushid forKey:@"pushid"];
        
        NSString *isJailbroken = nil;
        if([[UIDevice currentDevice] isJailbroken]){
            isJailbroken = @"YES";
        }else{
            isJailbroken = @"NO";
        }
        
        NSError *error;
        CFUUIDRef puuid = CFUUIDCreate( nil );
        CFStringRef uuidString = CFUUIDCreateString( nil, puuid );
        NSString * result = (NSString *)CFStringCreateCopy( NULL, uuidString);
        CFRelease(puuid);
        CFRelease(uuidString);
        if(![[SFHFKeychainUtils getPasswordForUsername:@"halfeet_user_UUID" andServiceName:@"com.halfeet_halfeet" error:&error] length])
        {
            [SFHFKeychainUtils storeUsername:@"halfeet_user_UUID" andPassword:result forServiceName:@"com.halfeet_halfeet" updateExisting:YES error:&error];
        }
        
        [result release];
        NSString *systemUDID = [SFHFKeychainUtils getPasswordForUsername:@"halfeet_user_UUID" andServiceName:@"com.halfeet_halfeet" error:&error];
        [loginDic setValue:[NSString stringWithFormat:@"%@::%@::%@::%@::%@::%@",[[UIDevice currentDevice] systemName],[[UIDevice currentDevice] systemVersion],[MyAppDataManager getPreferredLanguage],[[UIDevice currentDevice] platformString],isJailbroken,systemUDID] forKey:@"sysparam"];
        
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setValue:[[UIDevice currentDevice] systemVersion] forKey:@"osver"];
        NSString *deviceStr = [[UIDevice currentDevice] platformString];
        NSString *dev = nil;
        NSString *isp = nil;
        if([deviceStr rangeOfString:@"("].location != NSNotFound&&[deviceStr rangeOfString:@")"].location != NSNotFound)
        {
            isp = [deviceStr substringFromIndex:[deviceStr rangeOfString:@"("].location];
            dev = [deviceStr substringToIndex:[deviceStr rangeOfString:@"("].location];
        }
        //    NSLog(@"%@ %@",isp,dev);
        [dic setValue:isp forKey:@"isp"];
        [dic setValue:dev forKey:@"dev"];
        
        [dic setValue:[[UIDevice currentDevice] name] forKey:@"name"];
        [dic setValue:isJailbroken forKey:@"jail"];
        [loginDic setValue:dic forKey:@"phoneinfor"];
        
        
        [loginDic setValue:[MyAppDataManager getLanguageSubmitToServer] forKey:@"lang"];
        
        //yinlinlin 2014年08月08日15:24:12 先使用pushid，获取不到的情况下使用systemUDID
        BanBu_AppDelegate *ap = (BanBu_AppDelegate *)[UIApplication sharedApplication].delegate;
        
        if(ap.pushid&&ap.pushid.length)
        {
            [loginDic setValue:ap.pushid forKey:@"deviceid"];
        }
        else
        {
            
            [loginDic setValue:systemUDID forKey:@"deviceid"];
        }
        
        
        NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleVersionKey];
        [loginDic setValue:version forKey:@"version"];
        [self login:loginDic];
        
        
        self.navigationController.view.userInteractionEnabled = NO;
        [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"getMessage", nil) activityAnimated:YES];
    }
    
    
    
    
//    if(buttonIndex == 1){
        if(alertView.tag == 1){
            [self performSelector:@selector(complete:)];
            
        }
//    }
    else{
        if(alertView.tag == 2){
            
            [MyAppDataManager.regDic setValue:[UserDefaults valueForKey:@"pushid"] forKey:@"pushid"];
            [self registerUserWith:MyAppDataManager.regDic];
            self.navigationController.view.userInteractionEnabled =NO;
            [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"registering", nil) activityAnimated:YES];
        }
    }
    
}
#pragma mark - 注册用户 提交所有注册资料 存储在MyAppDataManager中的另添加设备号 "deviceid" 和推送号 “pushid”
-(void)registerUserWith:(NSMutableDictionary *)_registerInfo
{
    NSError *error;
    CFUUIDRef puuid = CFUUIDCreate( nil );
    CFStringRef uuidString = CFUUIDCreateString( nil, puuid );
    NSString * result = (NSString *)CFStringCreateCopy( NULL, uuidString);
    CFRelease(puuid);
    CFRelease(uuidString);
    if(![[SFHFKeychainUtils getPasswordForUsername:@"halfeet_user_UUID" andServiceName:@"com.halfeet_halfeet" error:&error] length])
    {
        [SFHFKeychainUtils storeUsername:@"halfeet_user_UUID" andPassword:result forServiceName:@"com.halfeet_halfeet" updateExisting:YES error:&error];
    }
    //yinlinlin 2014年08月08日15:24:12 先使用pushid，获取不到的情况下使用systemUDID
    BanBu_AppDelegate *ap = (BanBu_AppDelegate *)[UIApplication sharedApplication].delegate;
    
    if(ap.pushid&&ap.pushid.length)
    {
        [_registerInfo setValue:ap.pushid forKey:@"deviceid"];
    }
    else
    {
        NSString *systemUDID = [SFHFKeychainUtils getPasswordForUsername:@"halfeet_user_UUID" andServiceName:@"com.halfeet_halfeet" error:&error];
        [_registerInfo setValue:systemUDID forKey:@"deviceid"];
    }
    
//    srand((unsigned)time(0));
//    [_registerInfo setValue:[NSString stringWithFormat:@"%d",rand()] forKey:@"deviceid"];
    
    NSLog(@"%@",_registerInfo);
    [AppComManager getBanBuData:BanBu_Set_Register_User par:_registerInfo delegate:self];
    
}
- (void)login:(NSDictionary *)_loginDic
{
    [AppComManager getBanBuData:BanBu_Check_Login par:_loginDic delegate:self];
}
- (void)banbuRequestDidFinished:(NSDictionary *)resDic error:(NSError *)error
{
    NSLog(@"registerDic : %@",resDic);
    NSLog(@"registerERROR :%@",error);
    self.navigationController.view.userInteractionEnabled = YES;
    [TKLoadingView dismissTkFromView:self.view animated:YES afterShow:0.0];
    if(error)
    {
        if([AppComManager respondsDic:resDic isFunctionData:BanBu_Set_User_Avatar]){
            
            UIAlertView * alert= [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"uploadFailNotice", nil) message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"reUpload", nil), nil];
            alert.tag = 1;
            [alert show];
            [alert release];
            return;
        }
        else if([AppComManager respondsDic:resDic isFunctionData:BanBu_Set_Register_User])
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"noticeNotice", nil) message:NSLocalizedString(@"network_error", nil) delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"retry", nil), nil];
            [alert show];
            alert.tag = 111;
            [alert release];
        }
        else if([AppComManager respondsDic:resDic isFunctionData:BanBu_Check_Login])
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"noticeNotice", nil) message:NSLocalizedString(@"network_error", nil) delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"retry", nil), nil];
            [alert show];
            alert.tag = 222;
            [alert release];
        }
        else if([error.domain isEqualToString:BanBuDataformatError])
        {
            [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:2.0];
        }
        else
        {
            [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:2.0];
        }
        
        
        return;
    }
    
    if([AppComManager respondsDic:resDic isFunctionData:BanBu_Set_User_Avatar]){
        if([[resDic valueForKey:@"ok"] boolValue])
        {
            
            NSMutableDictionary *registerInfo = [NSMutableDictionary dictionary];
            [registerInfo setValue:[NSString stringWithFormat:@"%.f",AppLocationManager.curLocation.latitude*1000000] forKey:Latitude];
            [registerInfo setValue:[NSString stringWithFormat:@"%.f",AppLocationManager.curLocation.longitude*1000000] forKey:Longitude];
            [registerInfo setValue:[self getFacePath:[resDic valueForKey:@"smallpic"]] forKey:@"facepath"];
            [registerInfo setValue:[self getFaceName:[resDic valueForKey:@"smallpic"]] forKey:@"facefile"];
            [registerInfo setValue:[self getFaceName:[resDic valueForKey:@"largepic"]] forKey:@"facefull"];
            [self saveRegister:registerInfo];
            
            //弹出UIAlertView  点击确定进行登录操作
            UIAlertView * alert= [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"sysAvatarNotice", nil) message:NSLocalizedString(@"sysNoticeaaa", nil) delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"confirmNotice", nil),nil];
            alert.tag = 2;
            [alert show];
            [alert release];
            
        }else{
            [TKLoadingView showTkloadingAddedTo:self.view title:[MyAppDataManager IsInternationalLanguage:[resDic valueForKey:@"error"]] activityAnimated:NO duration:2.0];
        }
    }
    if([AppComManager respondsDic:resDic isFunctionData:BanBu_Set_Register_User]){
        if([[resDic valueForKey:@"ok"] boolValue])
        {
            NSMutableDictionary *loginDic = [NSMutableDictionary dictionary];
            [loginDic setValue:[MyAppDataManager.regDic valueForKey:@"email"] forKey:@"email"];
            [loginDic setValue:[MyAppDataManager.regDic valueForKey:@"pass"] forKey:@"pass"];
            [loginDic setValue:[NSString stringWithFormat:@"%.f",AppLocationManager.curLocation.latitude*1000000] forKey:@"plat"];
            [loginDic setValue:[NSString stringWithFormat:@"%.f",AppLocationManager.curLocation.longitude*1000000] forKey:@"plong"];
            [loginDic setValue:[MyAppDataManager.regDic valueForKey:@"regby"] forKey:@"regby"];
            
            BanBu_AppDelegate *delegate = (BanBu_AppDelegate *)[UIApplication sharedApplication].delegate;
            [loginDic setValue:delegate.pushid forKey:@"pushid"];
            
            NSString *isJailbroken = nil;
            if([[UIDevice currentDevice] isJailbroken]){
                isJailbroken = @"YES";
            }else{
                isJailbroken = @"NO";
            }
            
            NSError *error;
            CFUUIDRef puuid = CFUUIDCreate( nil );
            CFStringRef uuidString = CFUUIDCreateString( nil, puuid );
            NSString * result = (NSString *)CFStringCreateCopy( NULL, uuidString);
            CFRelease(puuid);
            CFRelease(uuidString);
            if(![[SFHFKeychainUtils getPasswordForUsername:@"halfeet_user_UUID" andServiceName:@"com.halfeet_halfeet" error:&error] length])
            {
                [SFHFKeychainUtils storeUsername:@"halfeet_user_UUID" andPassword:result forServiceName:@"com.halfeet_halfeet" updateExisting:YES error:&error];
            }
            [result release];
            NSString *systemUDID = [SFHFKeychainUtils getPasswordForUsername:@"halfeet_user_UUID" andServiceName:@"com.halfeet_halfeet" error:&error];
            [loginDic setValue:[NSString stringWithFormat:@"%@::%@::%@::%@::%@::%@",[[UIDevice currentDevice] systemName],[[UIDevice currentDevice] systemVersion],[MyAppDataManager getPreferredLanguage],[[UIDevice currentDevice] platformString],isJailbroken,systemUDID] forKey:@"sysparam"];
            
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic setValue:[[UIDevice currentDevice] systemVersion] forKey:@"osver"];
            NSString *deviceStr = [[UIDevice currentDevice] platformString];
            NSString *dev = nil;
            NSString *isp = nil;
            if([deviceStr rangeOfString:@"("].location != NSNotFound&&[deviceStr rangeOfString:@")"].location != NSNotFound)
            {
                isp = [deviceStr substringFromIndex:[deviceStr rangeOfString:@"("].location];
                dev = [deviceStr substringToIndex:[deviceStr rangeOfString:@"("].location];
            }
            //    NSLog(@"%@ %@",isp,dev);
            [dic setValue:isp forKey:@"isp"];
            [dic setValue:dev forKey:@"dev"];
            
            [dic setValue:[[UIDevice currentDevice] name] forKey:@"name"];
            [dic setValue:isJailbroken forKey:@"jail"];
            [loginDic setValue:dic forKey:@"phoneinfor"];
            
            
            [loginDic setValue:[MyAppDataManager getLanguageSubmitToServer] forKey:@"lang"];
            //yinlinlin 2014年08月08日15:24:12 先使用pushid，获取不到的情况下使用systemUDID
            BanBu_AppDelegate *ap = (BanBu_AppDelegate *)[UIApplication sharedApplication].delegate;
            
            if(ap.pushid&&ap.pushid.length)
            {
                [loginDic setValue:ap.pushid forKey:@"deviceid"];
            }
            else
            {
                
                [loginDic setValue:systemUDID forKey:@"deviceid"];
            }

            
            NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleVersionKey];
            [loginDic setValue:version forKey:@"version"];
            [self login:loginDic];
            
            
            self.navigationController.view.userInteractionEnabled = NO;
            [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"getMessage", nil) activityAnimated:YES];
        }
        else
        {
            if([[resDic allKeys] indexOfObject:@"error"] != NSNotFound)
            {
                UIAlertView * alert= [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"sysNotice", nil) message:[MyAppDataManager IsInternationalLanguage:[resDic valueForKey:@"error"]] delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"confirmNotice", nil),nil];
                alert.tag = 1231412;
                [alert show];
                [alert release];
            }
        }
    }
    else if([AppComManager respondsDic:resDic isFunctionData:BanBu_Check_Login]){
        
        
        if([[resDic valueForKey:@"ok"]boolValue]){
            MyAppDataManager.loginid = [resDic valueForKey:@"loginid"];
            MyAppDataManager.useruid = [resDic valueForKey:@"userid"];
            MyAppDataManager.userAvatar =[resDic valueForKey:@"uface"];
            //创建10张聊天记录表
            [MyAppDataManager initDetailChatMessageTable];
            [UserDefaults setValue:resDic forKey:MyAppDataManager.useruid];
            
            if(![[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"settings"]){
                NSMutableDictionary *settingsDic = [NSMutableDictionary dictionaryWithCapacity:2];
                [settingsDic setValue:[NSArray arrayWithObjects:[NSNumber numberWithBool:YES],[NSNumber numberWithBool:YES], nil] forKey:@"boolKey"];
                [settingsDic setValue:@"msg_1" forKey:@"MusicSwith"];
                [settingsDic setValue:@"send_0" forKey:@"sendMsgBoolKey"];//添加发消息声音提示
                [settingsDic setValue:[NSNumber numberWithBool:YES] forKey:@"systemset_friendreadstatus"];//发送消息已读状态设置
                [settingsDic setValue:[NSNumber numberWithBool:NO] forKey:@"setFollowsHidden"];//隐藏关注的人，默认为否，不隐藏
                
                [settingsDic setValue:[resDic valueForKey:@"hideme"] forKey:@"hideme"];
                [settingsDic setValue:[NSNumber numberWithBool:YES] forKey:@"visitYouNotification"];   //接收“我查看了你的个人资料”通知
                [settingsDic setValue:[NSNumber numberWithBool:YES] forKey:@"followYouNotification"];  //接收“我关注了你”通知
                [settingsDic setValue:[NSNumber numberWithBool:YES] forKey:@"takeCareNotification"];   //接收新用户注册通知
                [settingsDic setValue:[NSNumber numberWithBool:1] forKey:@"onceRun"];
                //保存当前本版号
                NSString  *versonPath =[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0] stringByAppendingPathComponent:@"data.dat"];
                NSMutableDictionary * versonDic = [NSKeyedUnarchiver unarchiveObjectWithFile:versonPath];
                NSString * versonString = MyAppDataManager.newVersionNumber;
                versonString = [versonString stringByReplacingOccurrencesOfString:@"." withString:@""];
                [versonDic setValue:versonString forKey:MyAppDataManager.useruid];
                NSData *listData = [NSKeyedArchiver archivedDataWithRootObject:versonDic];
                [listData writeToFile:versonPath atomically:YES];
                
                NSMutableDictionary *addDic = [NSMutableDictionary dictionaryWithDictionary:resDic];
                [addDic setValue:settingsDic forKey:@"settings"];
                [UserDefaults setValue:addDic forKey:MyAppDataManager.useruid];
            }
            else
            {
                NSMutableDictionary *settingsDic = [NSMutableDictionary dictionaryWithDictionary:[[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"settings"]];
                [settingsDic setValue:[resDic valueForKey:@"hideme"] forKey:@"hideme"];
                NSMutableDictionary *addDic = [NSMutableDictionary dictionaryWithDictionary:resDic];
                [addDic setValue:settingsDic forKey:@"settings"];
                [UserDefaults setValue:addDic forKey:MyAppDataManager.useruid];
            }
            [UserDefaults setValue:MyAppDataManager.useruid forKey:@"myID"];
            [UserDefaults synchronize];
            
            if([[MyAppDataManager.regDic valueForKey:@"regby"]isEqualToString:@"b"]){
                NSMutableDictionary *pars = [NSMutableDictionary dictionaryWithCapacity:2];
                if([[MyAppDataManager.regDic valueForKey:@"bindtype"]integerValue] == 2){
                    [pars setValue:@"twitter" forKey:@"bindto"];
                    [pars setValue:[NSString stringWithFormat:@"%@,%@,%@",[UserDefaults valueForKey:@"TAccessToken"],[UserDefaults valueForKey:@"TAccessTokenSecret"],[UserDefaults valueForKey:@"TUser"]] forKey:@"bindstring"];
                }else if([[MyAppDataManager.regDic valueForKey:@"bindtype"]integerValue] == 1){
                    [pars setValue:@"facebook" forKey:@"bindto"];
                    //            [pars setValue:[NSString stringWithFormat:@"%@,%@",nil,@""] forKey:@"bindstring"];
                    [pars setValue:[NSString stringWithFormat:@"%@,%@",[UserDefaults valueForKey:@"FBAccessToken"],[UserDefaults valueForKey:@"FBUser"]] forKey:@"bindstring"];
                }
                
                
                [AppComManager getBanBuData:BanBu_Set_User_accountbind par:pars delegate:self];
                self.navigationController.view.userInteractionEnabled = NO;
            }else{
                [UserDefaults setValue:@"" forKey:@"QUser"];
                [UserDefaults setValue:@"" forKey:@"sinaUser"];
                
                BanBu_AppDelegate *delegate = (BanBu_AppDelegate *)[UIApplication sharedApplication].delegate;
                delegate.logined = YES;
//                [delegate setViewController:YES];
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"videoVerify", nil) message:NSLocalizedString(@"verifyNoticeAlert", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"取消", nil) otherButtonTitles:NSLocalizedString(@"wantVerify", nil), nil];
                alertView.tag = 88888;
                [alertView show];
                [alertView release];
            }
            
            
        }
        else
        {
            if([[resDic allKeys] indexOfObject:@"error"] != NSNotFound)
            {
                UIAlertView * alert= [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"sysNotice", nil) message:[MyAppDataManager IsInternationalLanguage:[resDic valueForKey:@"error"]] delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"confirmNotice", nil),nil];
                alert.tag = 14142;
                [alert show];
                [alert release];
            }
        }
        
    }
    else if([AppComManager respondsDic:resDic isFunctionData:BanBu_Set_User_accountbind]){
        NSMutableDictionary *uidDic = [NSMutableDictionary dictionaryWithDictionary:[UserDefaults valueForKey:MyAppDataManager.useruid]];
        [uidDic setValue:[resDic valueForKey:@"bindlist"] forKey:@"bindlist"];
        [UserDefaults setValue:uidDic forKey:MyAppDataManager.useruid];
        [UserDefaults synchronize];
        
        
        
        
        BanBu_AppDelegate *delegate = (BanBu_AppDelegate *)[UIApplication sharedApplication].delegate;
        delegate.logined = YES;
//        [delegate setViewController:YES];
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"videoVerify", nil) message:NSLocalizedString(@"verifyNoticeAlert", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"取消", nil) otherButtonTitles:NSLocalizedString(@"wantVerify", nil), nil];
        alertView.tag = 88888;
        [alertView show];
        [alertView release];
        
    }
}
-(void)changeAvatar:(UIButton *)sender
{
    [_avatorView setImageWithURL:[NSURL URLWithString:[[_facelist objectAtIndex:sender.tag-1223] valueForKey:@"system_facefile"]]];
    _useDefaultImage = YES;
    selectIndex = sender.tag-1223;
}
- (NSString *)getFacePath:(NSString *)parStr{
    NSInteger start = 7;
    NSInteger end = [parStr rangeOfString:@"/photo" options:NSBackwardsSearch].location;
    return [parStr substringWithRange:NSMakeRange(start, end-start)];
}

- (NSString *)getFaceName:(NSString *)parStr{
    NSInteger start = [parStr rangeOfString:@"face/" options:NSBackwardsSearch].location+5;
    NSInteger end = parStr.length;
    return [parStr substringWithRange:NSMakeRange(start, end-start)];
}

#pragma show and hide the keyboard
- (void)setUpForDismissKeyboard {
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    UITapGestureRecognizer *singleTapGR =
    [[UITapGestureRecognizer alloc] initWithTarget:self
                                            action:@selector(tapAnywhereToDismissKeyboard:)];
    NSOperationQueue *mainQuene =[NSOperationQueue mainQueue];
    [nc addObserverForName:UIKeyboardWillShowNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note){
                    [self.view addGestureRecognizer:singleTapGR];
                }];
    [nc addObserverForName:UIKeyboardWillHideNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note){
                    [self.view removeGestureRecognizer:singleTapGR];
                }];
}

- (void)tapAnywhereToDismissKeyboard:(UIGestureRecognizer *)gestureRecognizer {
    //此method会将self.view里所有的subview的first responder都resign掉
    [self checkCanFinish];
    [self.view endEditing:YES];
}
- (void)viewDidUnload
{
    [super viewDidUnload];
    self.imagePathExtension = nil;
}
-(void)viewWillAppear:(BOOL)animated
{
    [UIView setAnimationsEnabled:YES];
    [super viewWillAppear:animated];
}
- (void)dealloc
{
    [_imagePathExtension release],_imagePathExtension = nil;
    [super dealloc];
}
@end
